package com.tang.sharding.algorithm;

import com.google.common.collect.Range;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Tang
 * @classname AbstractDateShardingAlgorithm
 * @description [  ]
 * @date 2021/8/3 17:26
 */
public abstract class AbstractDateShardingAlgorithm extends AbstractShardingAlgorithm<Date> {

    @Override
    public Collection<String> doRangeSharding(RangeShardingValue<Date> shardingValue) {
        Set<String> tableNamesSet = new HashSet<>(8);
        Range<Date> valueRange = shardingValue.getValueRange();
        // 起始值
        Date lowerEndpoint = valueRange.lowerEndpoint();
        LocalDateTime t1 = lowerEndpoint.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 结束值
        Date upperEndpoint = valueRange.upperEndpoint();
        LocalDateTime t2 = upperEndpoint.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        doDateRangeSharding(tableNamesSet, shardingValue, t1, t2);
        return tableNamesSet;
    }

    /**
     * 范围
     *
     * @param tableNamesSet tableNamesSet
     * @param shardingValue shardingValue
     * @param t1            t1
     * @param t2            t2
     * @return
     */
    protected abstract void doDateRangeSharding(Set<String> tableNamesSet,
                                                RangeShardingValue<Date> shardingValue,
                                                LocalDateTime t1, LocalDateTime t2);
}